<template>
  <section style="width: 100%">
    <div id="oss_input" name="oss_input" style="" >
      <div id="ossfile"></div>
      <div class="video-shade" @click="alertVideo" v-if="videoList.length >= 2"></div>
      <div id="video_container">
        <a id="selectfiles" href="javascript:void(0);" class="containeBtn" style="position: relative; z-index: 1; display:block;">
          <div class="select-video-wrapper">选择视频</div>
        </a>
        <!--<el-button v-if="url" type="primary" size="small" @click="videoBack">返回</el-button>-->
      </div>
      <div class="video-content">
        <div class="video" v-for="(item, index) in videoList">
          <span v-if="item.size">{{item.name}}({{item.size}})</span>&nbsp;&nbsp;
          <span v-if="item.url">{{item.name}}</span>&nbsp;&nbsp;
          <!--<span v-show="uploadEnd">上传成功</span>&nbsp;&nbsp;&nbsp;-->
          <el-button  v-show="item.url || proStatus" size="small" type="text" @click="deleteVideo(index)">删除</el-button>
        </div>
        <el-progress
          v-if="progress"
          :stroke-width="14"
          :percentage="progress"
          :status="proStatus"
        ></el-progress>
      </div>
    </div>
    <!--<el-row class="view-wrapper" v-show="url.length && !isEdit">-->
      <!--<el-col :span="4">{{name}}</el-col>-->
      <!--<el-col class="video-box" :span="16">-->
        <!--<video width="220" height="240" :src="url" controls="controls"></video>-->
      <!--</el-col>-->
      <!--<el-col :span="4" style="text-align: right">-->
        <!--<el-button size="small" type="primary" @click="isEdit = true">编辑</el-button>-->
      <!--</el-col>-->
    <!--</el-row>-->
  </section>
</template>

<script>
  import {Progress} from 'element-ui'
  import Plupload from 'plupload'
  import Crypto from '../common/upload/crypto'
  import Base64 from '../common/upload/base64'
  export default {
    data () {
      return {
        uploadData: '',
        accessid: '',
        accesskey: '',
        host: '',
        realityCount: 0,
        videoSize: '',
        videoName: '',
        progress: 0,
        uploadEnd: false,
        isEdit: false,
        proStatus: '',
        url: this.value,
        videoList: this.value,
        videoValue: []
      }
    },
    components: {
      ElProgress: Progress
    },
    props: {
      value: [String, Array],
      maxSize: {
        type: [Number, String],
        default: 1024
      },
      name: {
        type: String,
        default: ''
      },
      valueNum: {
        type: String,
        default: '1'
      },
      fileType: {
        type: String,
        default: 'avi,mp4,wmv,mov,FLV'
      }
    },
    watch: {
      value (data) {
        this.videoList = data
        if (data && ((data[0] && data[0].url) || (data[1] && data[1].url))) {
          this.videoValue = []
          data.map(item => {
            item.url && this.videoValue.push(item.url)
          })
        }
      }
    },
    methods: {
      deleteVideo (index) {
        this.videoValue.splice(index, 1)
        this.videoList.splice(index, 1)
        if (!this.videoList.length) {
          this.resetVideo()
        }
//        this.$emit('updateValue', this.videoValue)
      },
      resetVideo () {
        this.uploadEnd = false
        this.videoName = ''
        this.progress = 0
      },
      getName () {
        return this.videoValue
      },
      videoBack () {
        this.isEdit = false
        this.uploadEnd = false
        this.videoName = ''
        this.progress = 0
      },
      alertVideo () {
        this.$message.warning('最多上传两个视频！')
      },
      init () {
        let that = this
        let limit = this.$localStorage.get(this.$const.COOKIE.KEY_OSS)
        let uploadData = JSON.parse(Base64.decode(limit))
        let accessid = uploadData.accessKeyId
        let accesskey = uploadData.accessKeySecret
        let host = uploadData.endpoint.split('//')[0] + '//' + uploadData.inputBucket + '.' + uploadData.endpoint.split('//')[1]
        let fileCount = 0
        let Count = 0
        let gDirname = '' // product_video
        let gObjectName = ''
        let gObjectNameType = 'local_name'
        let policyText = {
          'expiration': '2020-01-01T12:00:00.000Z', // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
          'conditions': [
            ['content-length-range', 0, 1048576000] // 设置上传文件的大小限制
          ]
        }
        let policyBase64 = Base64.encode(JSON.stringify(policyText))
        let message = policyBase64
        let bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true})
        let signature = Crypto.util.bytesToBase64(bytes)
        function randomString (len) {
          len = len || 32
          var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
          var maxPos = chars.length
          var pwd = ''
          for (let i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos))
          }
          return pwd
        }
        function getSuffix (filename) {
          let pos = filename.lastIndexOf('.')
          let suffix = ''
          if (pos !== -1) {
            suffix = filename.substring(pos)
          }
          return suffix
        }
        function calculateObjectName (filename) {
          if (gObjectNameType === 'local_name') {
            var __name = gDirname + new Date().getTime() + '__' + filename
            gObjectName = __name
          } else if (gObjectNameType === 'random_name') {
            var suffix = getSuffix(filename)
            gObjectName = gDirname + randomString(10) + suffix
          }
//          let a = gObjectName.split('.')
//          a.pop()
//          gObjectName = a.join('.')
          return ''
        }
        function setUploadParam (up, filename, ret) {
          if (filename !== '') {
            calculateObjectName(filename)
          }

          var newMultipartParams = {
            'key': gObjectName,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', // 让服务端返回200,不然，默认会返回204
            'signature': signature
          }
          up.setOption({
            'url': host,
            'multipart_params': newMultipartParams
          })
          up.start()
        }

        let uploader = new Plupload.Uploader({
          runtimes: 'html5,flash,silverlight,html4',
          browse_button: 'selectfiles',
          multi_selection: that.valueNum === '2',
          container: document.getElementById('video_container'),
          flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
          silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
          url: 'http://oss.aliyuncs.com',
          // 文件过滤规则
          filters: {
            mime_types: [ // 只允许上传视频
              {title: 'Video files', extensions: that.fileType}
            ],
            max_file_size: that.maxSize + 'mb', // 最大只能上传3mb的文件
            prevent_duplicates: false // 不允许选取重复文件
          },
          init: {
            PostInit: function () {
              document.getElementById('ossfile').innerHTML = ''
              document.getElementById('selectfiles').onclick = function () {
//                setUploadParam(uploader, '', false)
                return false
              }
            },
            FilesAdded: function (up, files) {
              if (that.videoList.length + files.length > 2) {
                return that.$message.warning('最多只能上传2个视频！')
              }
              fileCount = files.length
              if (fileCount === 2) {
                that.videoValue = []
              }
              if (that.valueNum === '2') {
                if (files.length === 2 || that.videoList.length === 2) {
                  that.videoList = []
                }
              } else if (that.valueNum === '1') {
                that.videoList = []
              }
              Plupload.each(files, function (file) {
                that.videoList.push({
                  name: file.name,
                  id: file.id,
                  size: Plupload.formatSize(file.size)
                })
              })
              setUploadParam(uploader, '', false)
              this.realityCount = Count
            },
            BeforeUpload: function (up, file) {
              that.proStatus = ''
              setUploadParam(up, file.name, true)
            },
            UploadProgress: function (up, file) {
              that.progress = file.percent
            },
            FileUploaded: function (up, file, info) {
              if (info.status === 200) {
                that.uploadEnd = true
                that.proStatus = 'success'
                if (that.videoValue.length === 2 || fileCount === 2) {
                  if (that.videoValue.length !== 1) {
                    that.videoValue = []
                  }
                }
                if (that.valueNum === '1') {
                  that.videoValue = []
                }
                that.videoValue.push(gObjectName)
//                that.$emit('updateValue', that.videoValue)
              } else {
                that.$message.error(info.response)
              }
            },
            Error: function (up, err) {
              if (err.code === -600) {
                that.$message.error('视频大小超出限制')
              } else if (err.code === -601) {
                that.$message.error('文件类型不正确')
              } else {
                that.$message.error(err.message)
              }
            }
          }
        })
        uploader.init()
      }
    },
    mounted () {
      this.init()
    }
  }
</script>

<style lang='scss'>
.progress{
  border-radius: 5px;
  width: 0;
  height: 15px;
  background: #0081ff;
}
.video-shade{
  position: absolute;
  left: 0;
  top: 0;
  width: 300px;
  height: 50px;
  /*background: rgba(0, 255,255 ,.3);*/
  z-index: 999;
}
.video-content{
  min-width: 300px;
  .video-tips{
    color: #999;
    font-size: 12px;
    font-weight: 200;
  }
}
.el-progress{
  width: 60%;
}
  .view-wrapper{
    width: 100%;
    .video-box{
      /*height: 300px;*/
      video{
        /*height: 300px;*/
      }
    }
  }
.select-video-wrapper{
  display: block;
  padding: 0 10px;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  min-height: 40px;
  /* border: 1px solid red; */
  text-align: center;
  border: 1px solid #d8dce5;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  width: 100%;
  border-radius: 4px;
  line-height: 40px;
  color: #5a5e66;
  font-size: 14px;
  cursor: pointer;
  position: relative;
  color: #409eff;
}
</style>
